//
//  HYBroadCastViewModel.m
//  XPlayer
//
//  Created by 张水 on 2023/10/25.
//

#import "HYBroadCastViewModel.h"
#import <HYFTFFIleTransfer/HYBroadCastManager.h>
#import <HYFTFFIleTransfer/HYTCPServerManager.h>
#import <HYFTFFIleTransfer/HYSocketModel.h>
#import <Photos/Photos.h>
#import "HYHomeVideoModel.h"
#import "HYVideoModel.h"

@interface HYBroadCastViewModel ()

@property (nonatomic, strong) NSMutableArray *dataSoucre;

@end

@implementation HYBroadCastViewModel

- (instancetype)init
{
    if (self = [super init]) {
        self.dataSoucre = [NSMutableArray array];
        self.jumpSubJect = [RACSubject subject];
        [self congfigTCPServer];
    }
    return self;
}
- (void)dealloc
{
    NSLog(@"HYBroadCastViewModel  dealloc-------%@",self);
    [[HYBroadCastManager share] closeBroadCast];
    [[HYTCPServerManager share] closeServer];
}

- (void)congfigTCPServer
{
    [[HYTCPServerManager share] initSocket];
    BOOL accept = [HYTCPServerManager share].accept;
    if (accept) {
        NSLog(@"监听成功");
    }
    @weakify(self);
    [[HYTCPServerManager share] setReadData:^(NSData * _Nonnull data, NSString * _Nonnull fileName, NSString * _Nonnull type) {
        @strongify(self);
        if([type isEqualToString:@"text"]){
            return;
        }
        NSString *filePath = [self saveFileToDocumentWithData:data fileName:fileName];
        if (!filePath.length) {
            return;
        }
        [self creatFileModel:filePath];
    }];
}
- (NSString *)saveFileToDocumentWithData:(NSData *)data fileName:(NSString *)fileName
{
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentDir = [paths objectAtIndex:0];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager setAttributes:[NSDictionary dictionaryWithObject:NSFileProtectionNone forKey:NSFileProtectionKey] ofItemAtPath:documentDir error:NULL];
        BOOL isDir = NO;
        BOOL existed = [fileManager fileExistsAtPath:documentDir isDirectory:&isDir];
        if(!isDir && !existed){
            BOOL issucceed = [fileManager createDirectoryAtPath:documentDir withIntermediateDirectories:YES attributes:nil error:nil];
            NSLog(@"%d",issucceed);
        }
        NSError *error = nil;
        NSString *filePath = [documentDir stringByAppendingPathComponent:fileName];
        BOOL isSave = [data writeToFile:filePath options:NSDataWritingAtomic error:&error];
        if (!isSave) {
            [HYHub showMessage:NSLocalizedString(@"文件保存失败,请重新发送", nil)];
        }else{
            [HYHub showMessage:NSLocalizedString(@"文件保存成功", nil)];
        }
        return filePath;
}

- (void)creatFileModel:(NSString *)fileUrl
{
    NSString *lastName = [fileUrl lastPathComponent];
    HYHomeFileItemViewModel *videoModel = [[HYHomeFileItemViewModel alloc]init];
    videoModel.fileType = [[HYFileManager shareManager] fetchFileTypeWithFileName:fileUrl];
    videoModel.filePath = fileUrl;
    videoModel.fileName = lastName;
    NSString *createDate = [CommUtls encodeTimeYearMonthDay:[NSDate date]];
    videoModel.createDate = createDate;
    videoModel.importDate = createDate;
    NSString *time = [CommUtls fetchVideoDurationWithUrl:fileUrl];
    videoModel.videoDuration = time;
    videoModel.isHiddenSet = YES;
    videoModel.videoImage = [CommUtls fetchVideoCoverImageWithUrl:fileUrl atTime:1.0];
    videoModel.fileSize = [CommUtls fileLengthForPath:fileUrl];
    [self.updatedContentSignal sendNext:videoModel];
}

- (void)loadData:(ListData)listData
{
    @weakify(self);
    [[HYBroadCastManager share] configUDP];
    [[HYBroadCastManager share] setListBlock:^(NSArray * list) {
        @strongify(self);
        self.dataSoucre = [list copy];
        if (listData) {
            listData();
        }
    }];
}

- (NSInteger)numberOfRowsInSection:(NSInteger)section
{
    return self.dataSoucre.count;
}

- (id)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HYSocketModel *model = self.dataSoucre[indexPath.row];
    return model;
}

- (void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HYSocketModel *model = self.dataSoucre[indexPath.row];
    [self.jumpSubJect sendNext:model];
}


@end
